package com.vj.router.server.impl;

import com.vj.router.common.*;
import com.vj.router.server.util.GatewayRegistryMapCacheUtil;
import io.grpc.stub.StreamObserver;
import org.springframework.stereotype.Service;

@Service
public class RouterGatewayRegistryServiceImpl extends RouterGatewayRegistryServiceGrpc.RouterGatewayRegistryServiceImplBase {

    @Override
    public void registerRoute(RegisterGatewayRegistryRouteRequest request, StreamObserver<RegisterGatewayRegistryRouteResponse> responseObserver) {
        String gatewayId = request.getGatewayId();
        String registryId = request.getRegistryId();

        // 这里可以添加实际的业务逻辑，例如将设备和网关的映射关系保存到数据库中
        System.out.println("Registering route for gateway: " + gatewayId + " with registry: " + registryId);
        // 更新设备ID、和网关ID到 router-server 缓存中、或者存储redis中
        GatewayRegistryMapCacheUtil.putGatewayIdToRegistry(gatewayId, registryId);

        // 构建响应
        RegisterGatewayRegistryRouteResponse response = RegisterGatewayRegistryRouteResponse.newBuilder()
                .setMessage("Route registered successfully for gateway: " + registryId)
                .build();

        // 发送响应
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

    @Override
    public void getRoute(GetGatewayRegistryRouteRequest request, StreamObserver<GetGatewayRegistryRouteResponse> responseObserver) {
        String gatewayId = request.getGatewayId();

        // 这里可以添加实际的业务逻辑，例如从数据库中查询设备对应的网关
        String registryId = GatewayRegistryMapCacheUtil.getGatewayIdToRegistry(gatewayId);

        // 构建响应
        GetGatewayRegistryRouteResponse response = GetGatewayRegistryRouteResponse.newBuilder()
                .setGatewayId(gatewayId)
                .setMessage("Route found for gateway: " + registryId)
                .build();

        // 发送响应
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

    @Override
    public void unregisterRoute(UnregisterGatewayRegistryRouteRequest request, StreamObserver<UnregisterGatewayRegistryRouteResponse> responseObserver) {
        String gatewayId = request.getGatewayId();

        // 这里可以添加实际的业务逻辑，例如从数据库中删除设备和网关的映射关系
        System.out.println("Unregistering route for gateway: " + gatewayId);

        GatewayRegistryMapCacheUtil.removeGatewayIdToRegistry(gatewayId);

        // 构建响应
        UnregisterGatewayRegistryRouteResponse response = UnregisterGatewayRegistryRouteResponse.newBuilder()
                .setMessage("Route unregistered successfully for gateway: " + gatewayId)
                .build();

        // 发送响应
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }
}